$(function () {
    // redirect
    function redirect() {
      $.ajax({
        type: 'GET',
        async: false,
        timeout: 10000,
        url: 'https://h5.yajunuse.com/wechat/rediect',
        data: {
          url: location.href.split('#')[0],
          scope: 'snsapi_userinfo'
        },
        dataType:"json",
        error: function(XMLHttpRequest, textStatus, errorThrown){
            //alert("系统错误："+errorThrown);
        },
        success: function (res) {
          console.log('res', res)
          // wxReady(res.data)
        }
      })
    }
    redirect()

    // 获取openId
    function getOpenId() {
      $.ajax({
        type: 'GET',
        async: false,
        timeout: 10000,
        url: 'https://h5.yajunuse.com/wechat/rediect',
        data: {
          url: location.href.split('#')[0],
          scope: 'snsapi_userinfo'
        },
        dataType:"json",
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            //alert("系统错误："+errorThrown);
        },
        success: function (res) {
          console.log('res', res)
          // wxReady(res.data)
        }
      })
    }

    // 微信分享
    function wxReady(data) {
      var share = {
          title: 'Hello 2024',
          desc: '中信证券资管为您送寄语！',
          link: 'https://h5.yajunuse.com/h5/',
          icon: 'https://h5.yajunuse.com/h5/img/share-img.jpg'
      }
  
      wx.config({
          debug : false,
          appId : data.appId,
          timestamp : data.timestamp,
          nonceStr : data.nonceStr,
          signature : data.signature,
          jsApiList : data.jsApiList
        });
        wx.ready(function() {
          //分享给朋友
          wx.updateAppMessageShareData({
            title : share.title, // 分享标题
            desc : share.desc, // 分享描述
            link : share.link, // 分享链接
            imgUrl : share.icon, // 分享图标
            type : 'link', // 分享类型,music、video或link，不填默认为link
            success : function() {
              // 用户确认分享后执行的回调函数
              console.log('分享给朋友成功')
            },
            cancel : function() {
              // 用户取消分享后执行的回调函数
            }
          });
          wx.updateTimelineShareData({
            title : share.title, // 分享标题
            link : share.link, // 分享链接
            imgUrl : share.icon, // 分享图标
            success : function() {
              // 用户确认分享后执行的回调函数
              console.log('分享成功')
            },
            cancel : function() {
              // 用户取消分享后执行的回调函数
            }
          });
        });
  
        wx.error(function(res) {
          console.log(res.errMsg)
        });
  
      }
  
      // 初始化
      function wxInit() {
          var url = location.href.split('#')[0];
          $.ajax({
              type: 'GET',
              async: false,
              timeout: 10000,
              url: 'https://h5.yajunuse.com/wechat/getWxJsdk',
              data: {
                  url: url
              },
              dataType:"json",
              error: function(XMLHttpRequest, textStatus, errorThrown){
                  //alert("系统错误："+errorThrown);
              },
              success: function (res) {
                  // console.log('res', res)
                  wxReady(res.data)
              }
         })
  
      }
      wxInit()


    function getWxUerInfo() {
        var url = location.href.split('#')[0];
        $.ajax({
            type: 'GET',
            async: false,
            timeout: 10000,
            url: 'https://h5.yajunuse.com/wechat/getOpenid',
            data: {},
            dataType:"json",
            error: function(XMLHttpRequest, textStatus, errorThrown){
                //alert("系统错误："+errorThrown);
            },
            success: function (res) {
                console.log('res', res)
                wxReady(res.data)
            }
        })
    }
    // getWxUerInfo()


    // 初始化
    ms.reSet({
        dw: 900,
        dh: 1624,
        sw: 750,
        sh: 1200,
        complete: function () {
        }
    });

    var Height = $('body').height();
    $(window).resize(function() {
        $('body').height(Height);
    });

    // $('.stage-canvas').attr('width', window.innerWidth);
    // $('.stage-canvas').attr('height', window.innerHeight);

    // loading
    var imgArray = [
        "img/content.png", "img/loading-bg.png", "img/loukong.png", "img/page1.png", "img/snow.png",
        "img/theme-bg.png", "img/theme0.png", "img/theme1.png", "img/theme2.png", "img/white-logo.png"
    ];
    var blons = true;
    ms.loadings(imgArray, true, function (obj) {
        $('.load-progress p span').css('width', obj.bfb + '%');
        $('.load-num').html(obj.bfb + '%');
        if (obj.bfb >= 80 && blons) {
            blons = false;
            $('.container').css('opacity', 1);
            setTimeout(function () {
                $('.loading').fadeOut(500);
                $('.page1').fadeIn(500);
            }, 1000);
        };
    });
    $(".click-next").click(function () {
        $('.page1').fadeOut(200);
        // $('#start-content').fadeIn(300);
        // $('#select-content').fadeIn(300);
        $('#start-content').fadeIn(300);
    })
    $("#start-content").click(function () {
        $('#start-content').fadeOut(500);
        $('#select-content').fadeIn(500)
    })

    $(".blessing-text").click(function(){
        currentText = ''
        $(this).find('p').each(function() {
            currentText += $(this).text() + '$';
        });
        $(".blessing-text").removeClass("blessing-text-active")
        $(this).addClass("blessing-text-active")
        let result = ''
        currentText.split('$').forEach(function (item) {
            if (item) {
                result += `<p>${item}</p>`
            }
        })
        $('.content-text').html(result)
    });
    let index = 0
    // 当前选中的文案
    let currentText = '春风可待$美梦常在$这个新年当然是好运的邮差'
    $("#switch-text-btn").click(function(){
        $(`#box-${index}`).hide()
        index += 1
        if (index >= 3) {
            index = 0
        }
        const checkedText = [
            '美梦常在'
        ]
        let firstTextList = [
            '春风可待$美梦常在$这个新年当然是好运的邮差',
            '愿你一直$站在自己热爱的世界里$闪闪发光',
            '家人闲坐/灯火可亲$新年伊始/喜乐安宁',
        ]
        currentText = firstTextList[index]
        $(".blessing-text").removeClass("blessing-text-active")
        $(`#box-${index}`).fadeIn()
        $(`#box-${index}`).find('.blessing-text').first().addClass('blessing-text-active');
    })
    // 保存寄语
    $('.save-text').click(function (){
        if (!currentText || !currentText.length) {
            layer.open({
                content: '请先选择祝福语！'
                ,skin: 'msg'
                ,time: 3
            });
            return false
        }
        let result = ''
        currentText.split('$').forEach(function (item) {
            result += `<p>${item}</p>`
        })
        $('.content-text').html(result)
        $('.page2').fadeOut()
        $('.page3').fadeIn()
    })

    // 动画
    var bgmusic = document.getElementById('bgmusic');

    function audioAutoPlay(a) {
        try {
            a.play();
        } catch (e) {
        }
        document.addEventListener("WeixinJSBridgeReady", function () {
            a.play();
        }, false);
    }
    audioAutoPlay(bgmusic);

    // 音乐
    $('.bgmusic').on("touchstart", function (event) {
        event.preventDefault();
        if ($(this).attr("plays") == "play") {
            $(".bgmusic img").attr("src", "img/sound-off.png");
            $(".bgmusic").attr("plays", "paused");
            bgmusic.pause();
        } else {
            $(".bgmusic img").attr("src", "img/sound-on.png");
            $(".bgmusic").attr("plays", "play");
            bgmusic.play();
        }
    });

    var theme = 0;

    var stage = new createjs.Stage('stageCanvas'); //创建画布


    $('.change-btn').click(function () {
        theme += 1;
        if (theme > 2) {
            theme = 0;
        }
        $('.theme img').attr('src', 'img/theme' + theme + '.png');
    })

    $('.sure-btn').click(function () {
      var userName = $('.userInput').val()
      // var userName = '张三'
      if (!userName || !userName.length) {
        layer.open({
          content: '请输入你的名字！'
          ,skin: 'msg'
          ,time: 3
        })
        return false
      }
      if (userName.length > 6) {
        layer.open({
          content: '名字过长，请重新输入！'
          ,skin: 'msg'
          ,time: 3
        })
        return false
      }
      $('.page3').fadeOut();
      $('.page4').fadeIn();

      // 操作
        var bg = new createjs.Bitmap('img/theme-bg.png'); //创建背景图
        bg.regX = 0;
        bg.regY = 0;
        bg.x = 0;
        bg.y = 0; //设置背景图位置
        stage.addChild(bg); //放置背景图到canvas画布
        stage.update();
        function tick(event) {
          stage.update(event);
        }
        createjs.Ticker.setFPS(5);
        createjs.Ticker.addEventListener("tick", tick);

        var w = stage.canvas.width;
        // 插入主题
        var themeCanvas = new createjs.Bitmap('img/theme' + theme + '.png');
        themeCanvas.setTransform (75, 180, 0.95, 0.95)
        stage.addChild(themeCanvas);
        stage.update();
        // 插入文字
        var insertText = []
        currentText.split('$').forEach(function (item) {
          if (item) {
            insertText.push(new createjs.Text(item, "26px SiYuan", '#000000'))
          }
        })
        insertText.forEach(function(item, index) {
            item.x = (w - item.getBounds().width) / 2;
            if (theme === 2) {
                item.y = 755 + index * 55;
            } else {
                item.y = 700 + index * 55;
            }

            stage.addChild(item)
        })
        stage.update();
        // 插入logo
        var logoCanvas = new createjs.Bitmap('img/white-logo.png');
        logoCanvas.setTransform(75, 80, 0.8, 0.8)
        stage.addChild(logoCanvas);
        stage.update();
        // 底部文字
        var bottomText = new createjs.Text('市场有风险 投资需谨慎', "20px SiYuan", '#ffffff');
        bottomText.x = 90
        bottomText.y = 1260
        stage.addChild(bottomText);
        stage.update();
        
        // 插入二维码
        var qrcode = new createjs.Bitmap('img/qrcode.png');
        qrcode.setTransform(484, 1122, 0.9, 0.9)
        stage.addChild(qrcode);
        stage.update();
         // 插入雪花
         var snowflakeIcon = new createjs.Bitmap('img/icon-2.png');
         // 1160
         snowflakeIcon.setTransform(-35, 1130, 0.6, 0.6)
         stage.addChild(snowflakeIcon);
         stage.update();

        // 插入 from img
        var fromCanvas = new createjs.Bitmap('img/from.png');
        fromCanvas.setTransform(400, 950, 1, 1)
        stage.addChild(fromCanvas);
        stage.update();

        // 插入 用户名
        var userNameText = new createjs.Text(userName, "20px Microsoft YaHei bold", '#000');
        userNameText.x = 462
        userNameText.y = 938
        stage.addChild(userNameText);
        stage.update();



        var getCanvas = document.getElementById('stageCanvas');

        layer.open({
            type: 2,
            content: '合成中...'
        });

        setTimeout(function () {
          var imgData = getCanvas.toDataURL('image/jpeg', 0.8);
          $('.show-pic').attr('src', imgData);
          layer.closeAll();
          layer.open({
              content: '生成成功，请长按保存或者转发图片！'
              ,skin: 'msg'
              ,time: 5
          });
        }, 2000)

    })



})
